from pathlib import Path
from typing import Optional

from pony.orm import commit, db_session

from namer.models import File
from namer.videophash import PerceptualHash

abbreviations = {
    '18og': '18OnlyGirls',
    '18yo': '18YearsOld',
    '1kf': '1000Facials',
    '21ea': '21EroticAnal',
    '21fa': '21FootArt',
    '21n': '21Naturals',
    '2cst': '2ChicksSameTime',
    'Infr': 'InfernalRestraints',
    'a1o1': 'Asian1on1',
    'aa': 'AmateurAllure',
    'abbw': 'AbbyWinters',
    'abme': 'AbuseMe',
    'ad': 'AmericanDaydreams',
    'add': 'ManualAddActors',
    'agm': 'AllGirlMassage',
    'aktp': 'ATKPetites',
    'am': 'AssMasterpiece',
    'ana': 'AnalAngels',
    'analb': 'AnalBeauty',
    'atke': 'ATKExotics',
    'atkg': 'ATKGalleria',
    'atkgfs': 'ATKGirlfriends',
    'atkh': 'ATKHairy',
    'ba': 'BeautyAngels',
    'bam': 'BruceAndMorgan',
    'bblib': 'BigButtsLikeItBig',
    'bcast': 'BrutalCastings',
    'bcasting': 'BangCasting',
    'bcb': 'BigCockBully',
    'bch': 'BigCockHero',
    'bconfessions': 'BangConfessions',
    'bd': 'BrutalDildos',
    'bdpov': 'BadDaddyPOV',
    'bex': 'BrazzersExxtra',
    'bgb': 'BabyGotBoobs',
    'bgbs': 'BoundGangbangs',
    'bgfs': 'BlackGFS',
    'bglamkore': 'BangGlamkore',
    'bgonzo': 'BangGonzo',
    'bin': 'BigNaturals',
    'bjf': 'BlowjobFridays',
    'bna': 'BrandNew',
    'bp': 'ButtPlays',
    'bpu': 'BrutalPickups',
    'brealmilfs': 'BangRealMilfs',
    'brealteens': 'BangRealTeens',
    'btas': 'BigTitsAtSchool',
    'btaw': 'BigTitsAtWork',
    'btc': 'BigTitCreampie',
    'btis': 'BigTitsInSports',
    'btiu': 'BigTitsInUniform',
    'btlbd': 'BigTitsLikeBigDicks',
    'btp': 'BadTeensPunished',
    'btra': 'BigTitsRoundAsses',
    'burna': 'BurningAngel',
    'bwb': 'BigWetButts',
    'byngr': 'BangYNGR',
    'cc': 'CzechCasting',
    'cfnm': 'ClothedFemaleNudeMale',
    'cfnms': 'FNMSecret',
    'cfnmt': 'CFNMTeens',
    'cgfs': 'CzechGFS',
    'clip': 'LegalPorno',
    'cps': 'CherryPimps',
    'css': 'CzechStreets',
    'cuf': 'CumFiesta',
    'cws': 'CzechWifeSwap',
    'cza': 'CzechAmateurs',
    'czb': 'CzechBitch',
    'czbb': 'CzechBangBus',
    'czc': 'CzechCouples',
    'czestro': 'CzechEstrogenolit',
    'czf': 'CzechFantasy',
    'czgb': 'CzechGangBang',
    'czharem': 'CzechHarem',
    'czm': 'CzechMassage',
    'czo': 'CzechOrgasm',
    'czps': 'CzechPawnShop',
    'czt': 'CzechTwins',
    'cztaxi': 'CzechTaxi',
    'da': 'DoctorAdventures',
    'dbm': 'DontBreakMe',
    'dc': 'DorcelVision',
    'ddfb': 'DDFBusty',
    'ddfvr': 'DDFNetworkVR',
    'deb': 'DeviceBondage',
    'dlla': 'DaddysLilAngel',
    'dm': 'DirtyMasseur',
    'dnj': 'DaneJones',
    'doan': 'DiaryOfANanny',
    'dpf': 'DPFanatics',
    'dpg': 'DigitalPlayground',
    'ds': 'DungeonSex',
    'dsw': 'DaughterSwap',
    'dts': 'DeepThroatSirens',
    'dwc': 'DirtyWivesClub',
    'dwp': 'DayWithAPornstar',
    'esp': 'EuroSexParties',
    'ete': 'EuroTeenErotica',
    'ext': 'ExxxtraSmall',
    'fab': 'FuckedAndBound',
    'fams': 'FamilyStrokes',
    'faq': 'FirstAnalQuest',
    'fbbg': 'FirstBGG',
    'fds': 'FakeDrivingSchool',
    'ff': 'FilthyFamily',
    'ffr': 'FacialsForever',
    'fft': 'FemaleFakeTaxi',
    'fhd': 'FantasyHD',
    'fhl': 'FakeHostel',
    'fho': 'FakeHubOriginals',
    'fka': 'FakeAgent',
    'fm': 'FuckingMachines',
    'fms': 'FantasyMassage',
    'frs': 'FitnessRooms',
    'fs': 'FuckStudies',
    'ft': 'FastTimes',
    'ftx': 'FakeTaxi',
    'fum': 'FuckingMachines',
    'gbcp': 'GangbangCreampie',
    'gdp': 'GirlsDoPorn',
    'gfr': 'GFRevenge',
    'gft': 'GrandpasFuckTeens',
    'gta': 'GirlsTryAnal',
    'gw': 'GirlsWay',
    'h1o1': 'Housewife1on1',
    'ham': 'HotAndMean',
    'hart': 'Hegre',
    'hcm': 'HotCrazyMess',
    'hletee': 'HelplessTeens',
    'hoh': 'HandsOnHardcore',
    'hotab': 'HouseOfTaboo',
    'hotb': 'HouseOfTaboo',
    'ht': 'Hogtied',
    'ihaw': 'IHaveAWife',
    'iktg': 'IKnowThatGirl',
    'il': 'ImmoralLive',
    'inh': 'InnocentHigh',
    'itc': 'InTheCrack',
    'jlmf': 'JessieLoadsMonsterFacials',
    'kha': 'KarupsHA',
    'kow': 'KarupsOW',
    'kpc': 'KarupsPC',
    'la': 'LatinAdultery',
    'lang': 'LANewGirl',
    'lcd': 'LittleCaprice',
    'lhf': 'LoveHerFeet',
    'lsb': 'Lesbea',
    'lst': 'LatinaSexTapes',
    'lta': 'LetsTryAnal',
    'maj': 'ManoJob',
    'mbb': 'MommyBlowsBest',
    'mbc': 'MyBabysittersClub',
    'mbt': 'MomsBangTeens',
    'mc': 'MassageCreep',
    'mcu': 'MonsterCurves',
    'mdhf': 'MyDaughtersHotFriend',
    'mdhg': 'MyDadsHotGirlfriend',
    'mdm': 'MyDirtyMaid',
    'mfa': 'ManuelFerrara',
    'mfhg': 'MyFriendsHotGirl',
    'mfhm': 'MyFriendsHotMom',
    'mfl': 'Mofos',
    'mfp': 'MyFamilyPies',
    'mfst': 'MyFirstSexTeacher',
    'mgb': 'MommyGotBoobs',
    'mgbf': 'MyGirlfriendsBustyFriend',
    'mic': 'MomsInControl',
    'mj': 'ManoJob',
    'mlib': 'MilfsLikeItBig',
    'mlt': 'MomsLickTeens',
    'mmgs': 'MommysGirl',
    'mmp': 'MMPNetwork',
    'mnm': 'MyNaughtyMassage',
    'mot': 'MoneyTalks',
    'mpov': 'MrPOV',
    'mrs': 'MassageRooms',
    'mshf': 'MySistersHotFriend',
    'mts': 'MomsTeachSex',
    'mvft': 'MyVeryFirstTime',
    'mwhf': 'MyWifesHotFriend',
    'na': 'NaughtyAthletics',
    'naf': 'NeighborAffair',
    'nam': 'NaughtyAmerica',
    'nb': 'NaughtyBookworms',
    'news': 'NewSensations',
    'nf': 'NubileFilms',
    'no': 'NaughtyOffice',
    'nrg': 'NaughtyRichGirls',
    'nubilef': 'NubileFilms',
    'nubp': 'NubilesPorn',
    'num': 'NuruMassage',
    'nvg': 'NetVideoGirls',
    'nw': 'NaughtyWeddings',
    'obj': 'OnlyBlowjob',
    'oo': 'OnlyOpaques',
    'os': 'OnlySecretaries',
    'oss': 'OnlySilAndSatin',
    'otb': 'OnlyTeenBlowjobs',
    'pav': 'PixAndVideo',
    'pba': 'PublicAgent',
    'pbf': 'PetiteBallerinasFucked',
    'pc': 'PrincessCum',
    'pdmqfo': 'QuestForOrgasm',
    'pf': 'PornFidelity',
    'phd': 'PassionHD',
    'phdp': 'PetiteHDPorn',
    'plib': 'PornstarsLikeItBig',
    'pop': 'PervsOnPatrol',
    'ppu': 'PublicPickups',
    'prdi': 'PrettyDirty',
    'ps': 'PropertySex',
    'psp': 'PornstarsPunishment',
    'psus': 'PascalsSubSluts',
    'pud': 'PublicDisgrace',
    'rab': 'RoundAndBrown',
    'reg': 'RealExGirlfriends',
    'rkp': 'RKPrime',
    'rtb': 'RealTimeBondage',
    'rws': 'RealWifeStories',
    'saf': 'ShesAFreak',
    'sart': 'SexArt',
    'sas': 'SexAndSubmission',
    'sbj': 'StreetBlowjobs',
    'seb': 'SexuallyBroken',
    'sed': 'SexualDisgrace',
    'sislov': 'SisLovesMe',
    'sislove': 'SisLovesMe',
    'smb': 'ShareMyBF',
    'sr': 'SadisticRope',
    'ssc': 'StepSiblingsCaught',
    'ssn': 'ShesNew',
    'steps': 'StepSiblings',
    'stre': 'StrictRestraint',
    'sts': 'StrandedTeens',
    'swsn': 'SwallowSalon',
    't18': 'Taboo18',
    'taob': 'TheArtOfBlowJob',
    'tdp': 'TeensDoPorn',
    'tds': 'TheDickSuckers',
    'ted': 'Throated',
    'tf': 'TeenFidelity',
    'tfcp': 'FullyClothedPissing',
    'tft': 'TeacherFucksTeens',
    'tg': 'TopGrl',
    'tgs': 'ThisGirlSucks',
    'tgw': 'ThaiGirlsWild',
    'th': 'TwistysHard',
    'these': 'TheStripperExperience',
    'tla': 'TeensLoveAnal',
    'tlc': 'TeensLoveCream',
    'tle': 'TheLifeErotic',
    'tlhc': 'TeensLoveHugeCocks',
    'tlib': 'TeensLikeItBig',
    'tlm': 'TeensLoveMoney',
    'tmf': 'TeachMeFisting',
    'tog': 'TonightsGirlfriend',
    'togc': 'TonightsGirlfriendClassic',
    'trwo': 'TheRealWorkout',
    'tslw': 'SlimeWave',
    'tsm': 'TeenSexMovs',
    'tsma': 'TeenSexMania',
    'tspa': 'TrickySpa',
    'tss': 'ThatSitcomShow',
    'tt': 'TryTeens',
    'tto': 'TheTrainingOfO',
    'ttw': 'TeensInTheWoods',
    'tuf': 'TheUpperFloor',
    'vp': 'VIPissy',
    'wa': 'WhippedAss',
    'wfbg': 'WeFuckBlackGirls',
    'wgp': 'WhenGirlsPlay',
    'wkp': 'Wicked',
    'wlt': 'WeLiveTogether',
    'woc': 'WildOnCam',
    'wov': 'WivesOnVacation',
    'wowg': 'WowGirls',
    'wpa': 'WhippedAss',
    'wrh': 'WeAreHairy',
    'wy': 'WebYoung',
    'yt': 'YoungThroats',
    'zb': 'ZoliBoy',
    'ztod': 'ZeroTolerance',
    'zzs': 'ZZseries',
}

re_cleanup = [r'[0-9]{3,4}x[0-9]{3,4}', r'[0-9]{2}fps', r'[0-9]{3,4}p', r'[0-9]k', r'XXX.*', r'\[WEBDL-.*']


def safe_write_file_to_database(working_item: Path, phash: PerceptualHash):
    if not search_file_in_database(working_item):
        write_file_to_database(working_item, phash)


@db_session
def write_file_to_database(working_item: Path, phash: PerceptualHash):
    item_stats = working_item.stat()
    item_phash = str(phash.phash) if phash else None
    item_oshash = phash.oshash if phash else None

    File(file_name=working_item.name, file_size=item_stats.st_size, file_time=item_stats.st_mtime, duration=phash.duration, phash=item_phash, oshash=item_oshash)
    commit()


@db_session
def search_file_in_database(working_item: Path) -> Optional[File]:
    item_stats = working_item.stat()

    search_result = File.get(file_name=working_item.name, file_size=item_stats.st_size, file_time=item_stats.st_mtime)
    return search_result
